//
//  Path.m
//  Project
//
//  Created by Nguyen Tan Loc on 8/10/13.
//  Copyright (c) 2013 Nguyen Tan Loc. All rights reserved.
//

#import "Path.h"
#import "Utility.h"

@implementation Path

-(id) init
{
    if (self = [super init])
    {
        mListNode = [[NSMutableArray alloc] init];
        mListLine = [[NSMutableArray alloc] init];
        
        mBatchNode = [CCSpriteBatchNode batchNodeWithFile:IMAGE_INGAME];
        [self addChild:mBatchNode];
    }
    
    return self;
}

-(void) pushNode:(Node *)node
{
    [mListNode addObject:node];
    
    if (mListNode.count > 1)
    {
        Node *lastNode = [mListNode objectAtIndex:(mListNode.count - 2)];
        CGPoint sub = ccpSub(node.position, lastNode.position);
        
        Line *line = [[Line alloc] init];
        [line setPosition:lastNode.position];
        [line setLength:ccpLength(sub)];
        [line setAngle:[[Utility getInstance] vectorToAngle:sub]];
        
        [mListLine addObject:line];
        [line release];
    }
}

-(void) arrangeChild
{
    mCurrentNode = (Node *)[mListNode objectAtIndex:0];
    
    mIndicatorLine = [[Line alloc] init];
    [mIndicatorLine setVisible:NO];
    
    mIndicatorNode = [[Node alloc] init];
    [mIndicatorNode setVisible:NO];
    
    // add line first
    for (int i = 0; i < mListLine.count; i++)
    {
        Line *line = (Line *)[mListLine objectAtIndex:i];
        [mBatchNode addChild:line];
    }
    [mBatchNode addChild:mIndicatorLine];
    
    // add node after
    for (int i = 0; i < mListNode.count; i++)
    {
        Node *node = (Node *)[mListNode objectAtIndex:i];
        [mBatchNode addChild:node];        
        if (i != mListNode.count - 1)
        {
            Node *nextNode = (Node *)[mListNode objectAtIndex:(i + 1)];
            [node setNextNode:nextNode];
        }
    }
}

-(void) processTouch:(UITouchPhase)touchPhase position:(CGPoint)position
{
    if (touchPhase == UITouchPhaseBegan)
    {
//        CGRect rect = CGRectMake(mCurrentNode.position.x - mCurrentNode.contentSize.width / 2,
//                                 mCurrentNode.position.y - mCurrentNode.contentSize.height / 2,
//                                 mCurrentNode.contentSize.width,
//                                 mCurrentNode.contentSize.height);
//        if (CGRectContainsPoint(rect, position))
//        {
//            CCLOG(@"touch point");
//        }
    }
    else if (touchPhase == UITouchPhaseMoved)
    {
        
    }
    else if (touchPhase == UITouchPhaseEnded)
    {
        
    }
}

-(void) dealloc
{
    [super dealloc];
    
    [mListNode removeAllObjects];
    [mListNode release];
    mListNode = nil;
    
    [mListLine removeAllObjects];
    [mListLine release];
    mListLine = nil;
}

@end
